package com.wt.struggle.goodbye.main.activity

import android.app.Activity
import android.app.AlertDialog
import android.content.ContentValues
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import com.google.gson.reflect.TypeToken
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.MessageInfo
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.VideoInfo
import com.wt.struggle.goodbye.main.adapter.CommentAdapter
import com.wt.struggle.goodbye.sq.adapter.ContentImageAdapter
import com.wt.struggle.goodbye.user.activity.ShowImageActivity
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.ImageUtil
import com.xin.lv.yang.utils.utils.StatusBarUtil
import kotlinx.android.synthetic.main.comment_list_layout.*
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.pick_user_item.*

/**
 * 评论列表
 */
class CommentListActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

        when (what) {

            Send.COMMENT_LIST -> {

                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult

                    if (result != null && result != "") {
                        val arr: ArrayList<NewsInfo> =
                            gson!!.fromJson(result, object : TypeToken<ArrayList<NewsInfo>>() {}.type)

                        if (arr.size != 0) {
                            commentAdapter.updateDataClear(arr)

                            tvCommentNum.text = arr.size.toString()

                        } else {
                            showToastShort("无评论信息")
                        }

                    } else {
                        showToastShort("无评论信息")
                    }
                } else {
                    showToastShort("无评论信息")
                }
            }

            Send.DELETE_TIE -> {
                if (netInfo.code == Config.SUCCESS) {
                    page = 1
                    send!!.getCommentList(newInfo!!.id, page, handler)
                    showLoadDialog()
                }
            }
        }
    }

    val arr: ArrayList<NewsInfo> = arrayListOf()
    lateinit var commentAdapter: CommentAdapter


    private fun initAdapter() {

        commentListRecyclerView.isNestedScrollingEnabled = false
        commentListRecyclerView.layoutManager = LinearLayoutManager(this)
        commentListRecyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        commentAdapter = CommentAdapter(this, arr)
        commentListRecyclerView.adapter = commentAdapter

    }

    var page = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.comment_list_layout)

        val info = intent.getParcelableExtra<NewsInfo>("info")

        showInfo(info)

        tvTitle.text = info.topicName

        initAdapter()

        imageBack.setOnClickListener {
            finish()
        }


        send!!.getCommentList(info.id, page, handler)
        showLoadDialog()

        imageViewComment.setOnClickListener {
            commentSon(1, info)
        }

        /// 加入历史记录
        send!!.addHistoryList(info.id, handler)

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
    }

    var newInfo: NewsInfo? = null

    fun showInfo(info: NewsInfo) {

        this.newInfo = info

        imageCollect.visibility = View.INVISIBLE
        tvTextCollect.visibility = View.INVISIBLE
        imageViewZan.visibility = View.INVISIBLE
        tvZanNumber.visibility = View.INVISIBLE
        imageViewDown.visibility = View.INVISIBLE
        tvDownZanNum.visibility = View.INVISIBLE

        tvFocusOn.visibility = View.GONE
        imgMoreFocus.visibility = View.GONE
        linearIndex.visibility = View.GONE

        numberLinear.visibility = View.VISIBLE

        var videoList = intent.getParcelableArrayListExtra<VideoInfo>("vvvvList")
        var voiceList = intent.getParcelableArrayListExtra<VideoInfo>("audioList")

        log("---------$videoList---------$voiceList")


        if (videoList == null) {
            videoList = info.videoList
        }

        if (voiceList == null) {
            voiceList = info.audioList
        }

        if (videoList != null && videoList.size != 0) {

            val videoInfo = videoList[0]

            showVideo(videoInfo)

        } else if (info.picList != null && info.picList!!.size != 0) {
            showPic(info)

        } else if (voiceList != null && voiceList.size != 0) {
            val voiceInfo = voiceList[0]
            showVoice(voiceInfo)
        }


        tvContentMs.ellipsize = null
        tvContentMs.setSingleLine(false)

        tvContentName.text = info.topicName
        tvContentMs.text = DataUtil.getEmoji(this@CommentListActivity, info.content)
        tvTextCollect.text = info.collectionCount.toString()
        tvZanNumber.text = info.likeCount.toString()
        tvDownZanNum.text = "0"
        tvCommentNum.text = info.commentCount.toString()

        linearIndex.visibility = View.GONE

        val userInfo = info.userExtraInfo

        if (userInfo != null) {
            ImageUtil.getInstance()
                .loadCircleImage(this, sendImageUserHead, Config.GET_IMAGE_URL + userInfo.avatar, R.mipmap.logo_small)
            tvUserName.text = userInfo.nickName

            if (userInfo.isCollection == 1) {
                tvFocusOn.setBackgroundResource(R.drawable.gray_solid)
                tvFocusOn.setTextColor(resources.getColor(R.color.gray))
                tvFocusOn.text = "已关注"

            } else {
                tvFocusOn.setBackgroundResource(R.drawable.red_kuang_line)
                tvFocusOn.setTextColor(resources.getColor(R.color.red))
                tvFocusOn.text = "+关注"
            }

        }

        if (info.isCollection == 1) {

            imageCollect.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_y))
            tvTextCollect.setTextColor(resources.getColor(R.color.red))

        } else {
            imageCollect.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.coll_n))
            tvTextCollect.setTextColor(resources.getColor(R.color.black777))
        }


        if (info.isLike == 1) {

            imageViewZan.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.zan_y))
            tvZanNumber.setTextColor(resources.getColor(R.color.red))

        } else {
            imageViewZan.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.zan_n))
            tvZanNumber.setTextColor(resources.getColor(R.color.black777))
        }


    }


    /**
     * 显示图片
     */
    private fun showPic(info: NewsInfo) {

        log("显示图片-----------")
        layoutImageRecyclerView.visibility = View.VISIBLE
        videoParentFrame.visibility = View.GONE
        voiceLinearLayout.visibility = View.GONE

        val picListArr = info.picList

        layoutImageRecyclerView.isNestedScrollingEnabled = false

        if (picListArr != null && picListArr.size != 0) {

            val len = picListArr.size

            if (len != 0) {
                when (len) {
                    1 -> layoutImageRecyclerView.layoutManager = GridLayoutManager(this, 1)
                    2 -> layoutImageRecyclerView.layoutManager = GridLayoutManager(this, 2)
                    else -> layoutImageRecyclerView.layoutManager = GridLayoutManager(this, 3)

                }

                val picAdapter = ContentImageAdapter(this, picListArr, len, 1)

                layoutImageRecyclerView.adapter = picAdapter

                picAdapter.itemClickListener = object : ItemClickListener {

                    override fun onItemClick(position: Int) {

                        val strArr = arrayListOf<String>()

                        for (temp in picListArr) {
                            strArr.add(temp.domainname + temp.path.subSequence(1, temp.path.length))
                        }

                        val intent = Intent(this@CommentListActivity, ShowImageActivity::class.java)
                        intent.putStringArrayListExtra("arr", strArr)
                        startActivity(intent)
                    }

                    override fun onLongClick(position: Int) {
                    }

                }

            }
        }
    }

    var isFull = false

    /**
     * 显示视频
     */
    private fun showVideo(info: VideoInfo) {
        log("显示视频信息-----------")

        layoutImageRecyclerView.visibility = View.GONE
        videoParentFrame.visibility = View.VISIBLE
        voiceLinearLayout.visibility = View.GONE

        val path = info.domainname + info.path

        standardGSYVideoPlayer.clearThumbImageView()

        val imageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP

        ImageUtil.getInstance().loadVideoScreenshot(this, path, imageView, 0, null)

        standardGSYVideoPlayer.thumbImageView = imageView

        standardGSYVideoPlayer.setUpLazy(path, true, null, null, "")
        standardGSYVideoPlayer.titleTextView.visibility = View.GONE
        standardGSYVideoPlayer.backButton.visibility = View.GONE

        standardGSYVideoPlayer.onBackFullscreen()

        //设置全屏按键功能
        standardGSYVideoPlayer.fullscreenButton.setOnClickListener {
            standardGSYVideoPlayer.startWindowFullscreen(this, false, true)
            isFull = true
        }

        //防止错位设置
        standardGSYVideoPlayer.playTag = ContentValues.TAG

        //是否根据视频尺寸，自动选择竖屏全屏或者横屏全屏
        standardGSYVideoPlayer.isAutoFullWithSize = true
        //音频焦点冲突时是否释放
        standardGSYVideoPlayer.isReleaseWhenLossAudio = false
        //全屏动画
        standardGSYVideoPlayer.isShowFullAnimation = true
        //小屏时不触摸滑动
        standardGSYVideoPlayer.setIsTouchWiget(false)

        handler!!.postDelayed(Runnable {
            StatusBarUtil.setStatusBarLightMode(window, true)
        }, 300)

    }


    /**
     * 显示音频
     */
    private fun showVoice(voiceInfo: VideoInfo) {
        layoutImageRecyclerView.visibility = View.GONE
        videoParentFrame.visibility = View.GONE
        voiceLinearLayout.visibility = View.VISIBLE

        ///  播放音频
        val mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(voiceInfo.domainname + voiceInfo.path)
        mediaPlayer.prepareAsync()
        mediaPlayer.setOnPreparedListener {
            val dd = mediaPlayer.duration / 1000

            Log.i("result", "ddd------$dd")

            val scanW = getW()
            val w = scanW * dd / 60

            Log.i("result", "result------$w")

            tvVoiceLen.text = "${dd}s"

            val www = if (w > scanW * 1 / 3) {
                w
            } else {
                w + resources.getDimension(R.dimen.dp_40).toInt()
            }

            voiceLinearLayout.layoutParams =
                FrameLayout.LayoutParams(
                    www,
                    FrameLayout.LayoutParams.WRAP_CONTENT
                )

        }

        mediaPlayer.setOnCompletionListener {
            imageVoice.setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.play_voice))

        }


        imageVoice.setOnClickListener {
            mediaPlayer.start()
            ImageUtil.getInstance().loadImageGif(this, imageVoice, R.drawable.play_voice_gif)

        }

    }

    /**
     * 二级评论
     */
    fun commentSon(code: Int, info: NewsInfo) {
        val intent = Intent(this, AddCommentActivity::class.java)
        intent.putExtra("id", info.id)
        intent.putExtra("code", code)
        startActivityForResult(intent, 4455)

    }

    fun commentSon(code: Int, info: MessageInfo) {
        val intent = Intent(this, AddCommentActivity::class.java)
        intent.putExtra("id", info.id)
        intent.putExtra("code", code)
        startActivityForResult(intent, 4455)

    }

    fun showDelete(view: View, messageInfo: MessageInfo) {
        val build = AlertDialog.Builder(this)
        build.setMessage("是否删除该条评论信息?").setTitle("提示")
            .setPositiveButton("删除") { dd, _ ->

                deleteMessage(messageInfo)
                dd.dismiss()

            }.setNegativeButton("取消") { _, _ -> }.show()
    }

    private fun deleteMessage(messageInfo: MessageInfo) {
        if (messageInfo.appUserExtraInfo!!.appUserId == Share.getId(this).toString()) {
            send!!.deleteMessageInfo(messageInfo.id, handler)
        } else {
            showToastShort("该条评论不是您所发，您不能删除！！")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 4455 && resultCode == Activity.RESULT_OK) {
            send!!.getCommentList(newInfo!!.id, page, handler)
            showLoadDialog()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK && event!!.action == KeyEvent.ACTION_DOWN) {

            if (GSYVideoManager.isFullState(this)) {

                GSYVideoManager.backFromWindowFull(this)

            } else {
                finish()
            }

        }

        return super.onKeyDown(keyCode, event)
    }


}